package com.megvii.corelib.filechooser;

import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by linyue on 16/3/14.
 */
public class DevMountInfo
{
    private static DevMountInfo dev;

    /*
        #######################
        ## Regular device mount
        ##
        ## Format: dev_mount <label> <mount_point> <part> <sysfs_path1...>
        ## label        - Label for the volume
        ## mount_point  - Where the volume will be mounted
        ## part         - Partition # (1 based), or 'auto' for first usable partition.
        ## <sysfs_path> - List of sysfs paths to source devices
        ######################
        */
    public final String HEAD = "dev_mount";

    private final File VOLD_FSTAB = new File(Environment.getRootDirectory()
            .getAbsoluteFile() + File.separator + "etc" + File.separator + "vold.fstab");

    private ArrayList<String> cache = new ArrayList<String>();

    public static DevMountInfo getInstance()
    {
        if (null == dev)
        {
            dev = new DevMountInfo();
        }
        return dev;
    }

    /**
     * init the words into the cache array
     *
     * @throws IOException
     */
    private void initVoldFstabToCache()
    {
        try
        {
            cache.clear();
            BufferedReader br = new BufferedReader(new FileReader(VOLD_FSTAB));
            String tmp = null;
            while ((tmp = br.readLine()) != null)
            {
                // the words startsWith "dev_mount" are the SD info
                if (tmp.startsWith(HEAD))
                {
                    cache.add(tmp);
                    Log.v("xcl", tmp);
                }
            }
            br.close();
            cache.trimToSize();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public List<String> getStorageRoots()
    {
        initVoldFstabToCache();
        List<String> result = new ArrayList<>();
        for (String line : cache)
        {
            String[] sinfo = line.split(" |\t");
            if (sinfo.length >= 5)
            {
                String mountPoint = sinfo[2];
                result.add(mountPoint);
            }
        }
        return result;
    }
}
